<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>状态与周推荐数分析 - 纵横小说推荐榜数据可视化平台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/chart-styles.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
</head>
<body>
    <!-- 顶部区域 -->
    <header class="header">
        <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo" class="logo">
        <h1 class="system-title">纵横小说推荐榜数据可视化平台</h1>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
        <a href="/" class="nav-item">
            <i class="fas fa-book-open fa-fw"></i>
            <span>图书列表</span>
        </a>
        <a href="/charts" class="nav-item">
            <i class="fas fa-chart-pie fa-fw"></i>
            <span>书籍类别分布</span>
        </a>
        <a href="/bar-chart" class="nav-item">
            <i class="fas fa-chart-bar fa-fw"></i>
            <span>类别点击量分析</span>
        </a>
        <a href="/line-chart" class="nav-item">
            <i class="fas fa-chart-line fa-fw"></i>
            <span>字数与推荐数关系</span>
        </a>
        <a href="/boxplot" class="nav-item active">
            <i class="fas fa-chart-simple fa-fw"></i>
            <span>状态与周推荐数</span>
        </a>
        <a href="/ranking-chart" class="nav-item">
            <i class="fas fa-trophy fa-fw"></i>
            <span>书籍点击量排名</span>
        </a>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
        <h2 class="page-title">状态与周推荐数</h2>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-chart-simple"></i>
                    不同状态书籍的周推荐数分布
                </h3>
                <div class="chart-actions">
                    <button id="downloadBtn" class="action-button">
                        <i class="fas fa-download"></i>
                        <span>下载图表</span>
                    </button>
                    <button id="refreshBtn" class="action-button">
                        <i class="fas fa-sync-alt"></i>
                        <span>刷新数据</span>
                    </button>
                </div>
            </div>

            <div class="chart-description">
                <i class="fas fa-info-circle"></i>
                <p>此图表展示了纵横小说推荐榜中不同状态（连载中、已完结等）书籍的周推荐数分布情况，通过箱线图可以直观地比较不同状态书籍的推荐数中位数、四分位数范围以及异常值。</p>
            </div>

            <div id="loadingIndicator" class="loading">
                <div class="loading-spinner"></div>
            </div>

            <div id="chart" class="chart"></div>
        </div>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-table"></i>
                    状态分布统计
                </h3>
            </div>

            <div class="stats-grid">
                <div class="stats-card" id="totalBooksCard">
                    <div class="stats-icon">
                        <i class="fas fa-book"></i>
                    </div>
                    <div class="stats-content">
                        <div class="stats-title">总书籍数</div>
                        <div class="stats-value" id="totalBooksValue">计算中...</div>
                        <div class="stats-desc">分析中的总书籍数量</div>
                    </div>
                </div>

                <div class="stats-card" id="serializedCard">
                    <div class="stats-icon">
                        <i class="fas fa-pen"></i>
                    </div>
                    <div class="stats-content">
                        <div class="stats-title">连载中</div>
                        <div class="stats-value" id="serializedValue">计算中...</div>
                        <div class="stats-desc">连载中书籍的平均周推荐数</div>
                    </div>
                </div>

                <div class="stats-card" id="completedCard">
                    <div class="stats-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stats-content">
                        <div class="stats-title">已完结</div>
                        <div class="stats-value" id="completedValue">计算中...</div>
                        <div class="stats-desc">已完结书籍的平均周推荐数</div>
                    </div>
                </div>

                <div class="stats-card" id="comparisonCard">
                    <div class="stats-icon">
                        <i class="fas fa-balance-scale"></i>
                    </div>
                    <div class="stats-content">
                        <div class="stats-title">状态对比</div>
                        <div class="stats-value" id="comparisonValue">计算中...</div>
                        <div class="stats-desc">连载/完结推荐数比值</div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        // 初始化ECharts实例
        var chartDom = document.getElementById('chart');
        var myChart = echarts.init(chartDom);

        var boxplotData = [];

        // 显示加载状态
        function showLoading() {
            document.getElementById('loadingIndicator').style.display = 'flex';
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loadingIndicator').style.display = 'none';
        }

        // 计算箱线图数据
        function prepareBoxplotData(rawData) {
            const result = [];
            const categories = [];
            const statistics = {};
            let totalBooks = 0;

            // 处理每个状态的数据
            rawData.forEach(item => {
                const status = item.status;
                categories.push(status);

                // 计算箱线图所需的统计值
                const data = item.data.sort((a, b) => a - b);
                const len = data.length;
                totalBooks += len;

                // 计算平均值
                const sum = data.reduce((acc, val) => acc + val, 0);
                const mean = sum / len;

                statistics[status] = {
                    count: len,
                    mean: mean.toFixed(2)
                };

                result.push({
                    name: status,
                    type: 'boxplot',
                    data: [calculateBoxData(data)],
                    tooltip: {
                        formatter: function(param) {
                            return [
                                `${param.name}: `,
                                `上边缘: ${param.data[5].toFixed(2)}`,
                                `上四分位: ${param.data[4].toFixed(2)}`,
                                `中位数: ${param.data[3].toFixed(2)}`,
                                `下四分位: ${param.data[2].toFixed(2)}`,
                                `下边缘: ${param.data[1].toFixed(2)}`,
                                `平均值: ${mean.toFixed(2)}`,
                                `样本数: ${len}`
                            ].join('<br/>');
                        }
                    }
                });

                // 添加异常值
                const outliers = findOutliers(data);
                if (outliers.length > 0) {
                    result.push({
                        name: status + ' 异常值',
                        type: 'scatter',
                        data: outliers.map(value => {
                            return [categories.indexOf(status), value];
                        }),
                        itemStyle: {
                            color: '#f5222d'
                        }
                    });
                }
            });

            // 更新统计卡片
            document.getElementById('totalBooksValue').textContent = totalBooks;

            if (statistics['连载中'] && statistics['已完结']) {
                document.getElementById('serializedValue').textContent = statistics['连载中'].mean;
                document.getElementById('completedValue').textContent = statistics['已完结'].mean;

                const ratio = (statistics['连载中'].mean / statistics['已完结'].mean).toFixed(2);
                document.getElementById('comparisonValue').textContent = ratio;
            }

            return {
                series: result,
                categories: [...new Set(categories)]
            };
        }

        // 计算箱线图数据
        function calculateBoxData(data) {
            const len = data.length;

            // 排序后的数据
            const sortedData = [...data].sort((a, b) => a - b);

            // 计算四分位数
            const q1Index = Math.floor(len * 0.25);
            const q2Index = Math.floor(len * 0.5);
            const q3Index = Math.floor(len * 0.75);

            const q1 = sortedData[q1Index];
            const q2 = sortedData[q2Index];
            const q3 = sortedData[q3Index];

            // 计算IQR和边界
            const iqr = q3 - q1;
            const lowerBound = Math.max(sortedData[0], q1 - 1.5 * iqr);
            const upperBound = Math.min(sortedData[len - 1], q3 + 1.5 * iqr);

            // 返回箱线图数据格式 [min, q1, median, q3, max]
            return [lowerBound, q1, q2, q3, upperBound];
        }

        // 查找异常值
        function findOutliers(data) {
            const len = data.length;
            const sortedData = [...data].sort((a, b) => a - b);

            const q1Index = Math.floor(len * 0.25);
            const q3Index = Math.floor(len * 0.75);

            const q1 = sortedData[q1Index];
            const q3 = sortedData[q3Index];

            const iqr = q3 - q1;
            const lowerBound = q1 - 1.5 * iqr;
            const upperBound = q3 + 1.5 * iqr;

            return sortedData.filter(value => value < lowerBound || value > upperBound);
        }

        // 获取图表数据
        async function fetchChartData() {
            showLoading();

            try {
                const response = await fetch('/api/status-recommendations');
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }

                const rawData = await response.json();
                const { series, categories } = prepareBoxplotData(rawData);

                // 配置选项
                const option = {
                    title: {
                        text: '不同状态书籍的周推荐数分布',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '10%',
                        right: '10%',
                        bottom: '15%'
                    },
                    xAxis: {
                        type: 'category',
                        data: categories,
                        boundaryGap: true,
                        nameGap: 30,
                        splitArea: {
                            show: false
                        },
                        axisLabel: {
                            formatter: '{value}'
                        },
                        splitLine: {
                            show: false
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '周推荐数(万)',
                        splitArea: {
                            show: true
                        }
                    },
                    series: series
                };

                myChart.setOption(option);
            } catch (error) {
                console.error('获取数据失败:', error);
                myChart.showLoading({
                    text: '数据加载失败，请刷新重试',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    textColor: '#ff4d4f'
                });
            } finally {
                hideLoading();
            }
        }

        // 下载图表
        document.getElementById('downloadBtn').addEventListener('click', function() {
            const link = document.createElement('a');
            link.download = '状态与周推荐数分析.png';
            link.href = myChart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#fff'
            });
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // 刷新数据
        document.getElementById('refreshBtn').addEventListener('click', fetchChartData);

        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            myChart.resize();
        });

        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', fetchChartData);
    </script>
</body>
</html>
